(function($){
    function groupBy(list, key){
        var map = {};
        if(!(list && list.length)){
            return map;
        }
        for(var i = 0; i < list.length; i++){
            var item = list[i];
            var k = item[key];
            var arr = map[k];
            if(!arr){
                arr = [];
                map[k] = arr;
            }
            arr.push(item);
        }
        return map;
    }
    function createElement(tagName, value, innerHTML, callback){
        var e = document.createElement(tagName);
        e.value = value;
        e.innerHTML = innerHTML;
        if(callback instanceof Function){
            callback(e);
        }
        return e;
    }
    $.fn.iDistpicker = function(config){
        var __debug = true;
        var __this = this;
        var __selects = __this.find("select");

        __debug && console.log(config);
        if(!(config && config.dataUrl)){
            throw "required data url";
        }
        function init(){
            getData(function(data){
                if(!(data && data.length)){
                    throw "there is no data";
                }
                data.reverse()
                var pc = groupBy(data, "type");
                var province = parseInt(config.province) || pc[1][0].id;
                renderSelect(__selects[0], pc[1], parseInt(config.province), 1);
                var cityList = pc[2];
                var pcMap = groupBy(cityList, "pid");
                renderSelect(__selects[1], pcMap[province], parseInt(config.city), 2);
                __selects.eq(0).on("change", function(){
                    renderSelect(__selects[1], pcMap[parseInt(this.value)], null, 2);
                })
            })
        }
        function renderSelect(select, items, selected, type){
            var jqE = $(select);
            jqE.empty();
            jqE.append(createElement("option", "", type == 1? "ââéæ©çââ": type == 2? "ââéæ©å¸ââ": "ââè¯·éæ©ââ"));
            for(var i = 0; i < items.length; i++){
                var op = createElement("option", items[i].id, items[i].name);
                if(selected && selected === items[i].id){
                    op.setAttribute("selected", "selected");
                }
                jqE.append(op);
            }
        }
        function getData(callback){
            $.post(config.dataUrl, {}, function(data){
                callback(data);
            });
        }

        init();
    }
})($)